package com.qf.flash.http;


import android.support.annotation.NonNull;

import com.qf.flashlib.config.Constants;
import com.qf.flashlib.http.HttpLogUtil;
import com.qf.flashlib.http.converter.GsonDConverterFactory;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Retrofit操纵类
 */
public class HttpManager {
    private static volatile HttpManager instance;

    private OkHttpClient.Builder okHttpClientBuilder;
    private HttpLoggingInterceptor loggingInterceptor;
    private volatile HttpApi api;

    private HttpManager() {
        //构造OkHttpClient
        okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(Constants.HTTP_DEFAULT_TIME, java.util.concurrent.TimeUnit.SECONDS);
        okHttpClientBuilder.addInterceptor(getLoggingInterceptor());
    }

    /**
     * 动态令牌
     */
    public static HttpManager getInstance() {
        if (instance == null) {
            synchronized (HttpManager.class) {
                if (instance == null) {
                    instance = new HttpManager();
                }
            }
        }
        return instance;
    }


    /**
     * 获取Gson解析的HttpApi
     */
    public HttpApi getGsonHttpApi() {
        if (api == null) {
            synchronized (HttpManager.class) {
                api = new Retrofit
                        .Builder()
                        .client(okHttpClientBuilder.build())
                        .baseUrl(ApiHost.DEV_BASE)
                        .addConverterFactory(GsonDConverterFactory.create())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build()
                        .create(HttpApi.class);
            }
        }
        return api;
    }

    /**
     * 获取打印拦截器
     */
    private HttpLoggingInterceptor getLoggingInterceptor() {
        if (loggingInterceptor == null) {
            loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(@NonNull String message) {
                    HttpLogUtil.log(Constants.HTTP_LOG_TAG, message);
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }
        return loggingInterceptor;
    }

}
